package com.learn.algorithm_1_march;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class BubbleSortTest {

    private static final int[] array = {64, 34, 25, 12, 22, 11, 90};

    // 选择排序，从第一个跟它之后的所有元素比较
    @Test
    public void chooseSortTest() {
        for (int i = 0; i < array.length; i++) {
            for (int j = i+1; j < array.length; j++) {
                System.out.println("i,j: " + i +"," +j);
                if (array[i] > array[j]) {
                    int before = array[i];
                    array[i] = array[j];
                    array[j] = before;
                }
            }
        }
        List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList());
        System.out.println(list);
    }

    // 冒泡排序，从第一个依次往后，每次比较相邻的两个元素，满足条件就互换位置
    @Test
    public void bubbleSortTest() {
        int n = array.length;

        for (int i = 0; i < n - 1; i++ ) {
            // 每一轮排序，会确定一个靠右（从大到小）的元素位置，因此逐渐缩小右侧边界，缩小j
            for (int j = 0; j < n - 1 - i; j++ ) {
                int Jnext = j + 1;
//                System.out.println("i,j,Jnext: " + i + "," + j +"," +Jnext);
                if (array[j] > array[Jnext]) {
                    int big = array[j];
                    array[j] = array[Jnext];
                    array[Jnext] = big;
                }
            }
        }
        List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList());
        System.out.println(list);
    }

}
